<template>
  <div class="tree">
    <div
      class="inputs"
      v-if="
        searchQx && searchQx.length
          ? $hasOneOf(searchQx, $store.state.user.access)
          : true
      "
    >
      <el-input
        placeholder="搜索部门名称"
        suffix-icon="el-icon-search"
        v-model="filterText"
        clearable
        size="small"
      >
      </el-input>
    </div>

    <div class="tree-box mt-9">
      <el-tree
        class="filter-tree"
        :data="data"
        :props="defaultProps"
        :default-expand-all="false"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        :default-expanded-keys="defaultKeys"
        :highlight-current="true"
        ref="tree"
        node-key="id"
        @node-click="nodeClick"
      >
        <div class="custom-tree-node" slot-scope="{ node, data }">
          <el-tooltip
            class="item"
            effect="dark"
            :content="data.name"
            placement="top-start"
            :open-delay="500"
          >
            <div class="box">
              <span class="tag" v-if="node.level == 3 && !noTag">{{
                formatterOrg(data.orgType)
              }}</span>
              <span class="name">{{ data.name }}</span>
            </div>
          </el-tooltip>
        </div>
      </el-tree>
    </div>
  </div>
</template>

<script>
import axios from "@/libs/api.request";
import { mapState } from "vuex";
export default {
  name: "tree",
  props: {
    value: {
      type: Object,
    },
    url: {
      type: String,
      default: () => "/org/trends/tree",
    },
    searchQx: {
      type: Array,
      default: () => {
        return [];
      },
    },
    queryName: {
      type: String,
    },
    platType: {
      type: String,
      default: () => "BOOKING",
    },
    editId: {
      type: String,
      default: () => "",
    },
    // 是否需要索引到子集
    isFindChild: {
      type: Boolean,
      default: () => false,
    },
    // 是否提示‘请先保存此条数据’
    showEdit: {
      type: Boolean,
      default: () => false,
    },
    // 是否提示‘切换到xxx数据’
    showAdd: {
      type: Boolean,
      default: () => false,
    },
    node: {
      type: Object,
      default: () => {},
    },
    // 不显示标签
    noTag: {
      type: Boolean,
      default: () => false,
    },
    // 是否禁用第四等级
    disFour: {
      type: Boolean,
      default: () => false,
    },
    // 请求参数
    requestData: {
      type: Object,
      default: () => {},
    },
    // 请求方式
    requestMethod: {
      type: String,
      default: () => "get",
    },
  },
  data() {
    return {
      data: [],
      filterText: "",
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: (data, node) => {
          if (!data.children || data.children.length == 0) {
            return true;
          }
        },
      },
      defaultKeys: [],
      treeData: {},
      orgEnu: [],
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    value: {
      handler(nval) {
        if (nval) {
          this.treeData = nval;
        }
      },
    },
  },
  mounted() {
    // 获取枚举
    this.$getEnumerations([{ type: "auth", code: 9, name: "orgEnu" }]).then(
      (res) => {
        this.orgEnu = res.orgEnu;
      }
    );
    // 获取列表数据
    this.getTreeList();
  },

  methods: {
    // 过滤组织类型
    formatterOrg(type) {
      return this.orgEnu.find((el) => el.value == type)?.name;
    },
    // 获取列表数据
    getTreeList(val = {}) {
      var obj = {};
      if (this.requestMethod == "post") {
        obj["data"] = Object.assign(this.requestData || {}, {
          userId: this.userInfo.id,
        });
      } else {
        obj["params"] = Object.assign(this.requestData || {}, {
          userId: this.userInfo.id,
        });
      }
      axios
        .request({
          url: this.$platform[this.platType] + this.url,
          method: this.requestMethod,
          ...obj,
        })
        .then((res) => {
          if (res.data.length) {
            this.data = res.data;
            this.$nextTick(function () {
              // 是否过滤出第一个树形结构的最后一个子值
              var arr = {};
              if (Object.keys(val)?.length) {
                arr = this.treeData;
              } else {
                arr = this.isFindChild
                  ? this.filterChildren(res.data[0])
                  : res.data[0];
              }

              // 设置默认
              this.$refs.tree.setCurrentKey(arr.id);
              // 抛出默认数据
              this.$emit("input", arr);
              // 设置默认展开
              this.defaultKeys = [arr.id];

              // 默认抛出node
              this.$emit("update:node", this.$refs.tree.getNode(arr.id));
              // 默认抛出treeData
              this.$emit("input", this.$refs.tree.getNode(arr.id).data);
              // this.$parent[this.queryName](res.data[0].id);
            });
          }
        })
        .catch((err) => {
          this.$Message.error(err?.msg);
        });
    },
    filterChildren(arr) {
      if (arr.children && arr.children.length) {
        var child = arr.children;
        return this.filterChildren(child[0]);
      } else {
        return arr;
      }
    },
    // 过滤内容
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 以下两个方法结果一样
    // 根据‘节点’向上查询所有id
    getParentId(node, ids = []) {
      if (node.parent && node.parent.data) {
        ids.unshift({ id: node.data.id, label: node.label });
        this.getParentId(node.parent, ids);
      }
      return ids;
    },
    // 根据‘组织id和treeList’向上查询所有id
    getAllOrgId(arr, node, ids = []) {
      arr.forEach((it, index) => {
        if (node.data.constructor == Object && node.data.id == it.id) {
          ids.unshift(it.id);
          this.getAllOrgId(this.data, node.parent, ids);
        }
        if (it.children && it.children.length) {
          this.getAllOrgId(it.children, node, ids);
        }
      });
      return ids;
    },
    // ending...
    // 节点点击
    nodeClick(data, node) {
      if (this.disFour && node.level == 4) {
        this.$Message.error("无法点击");
        // 设置激活
        this.$refs.tree.setCurrentKey(this.treeData.id);
      } else {
        if (this.showEdit) {
          this.$Message.error("请先保存此成员信息");
          // 设置激活
          this.$refs.tree.setCurrentKey(this.treeData.id);
        } else {
          if (this.showAdd) {
            this.$Message.warning(
              "当前切换到" +
                this.getParentId(node)
                  .map((it) => it.label)
                  .join("/")
            );
          }
          this.treeData = data;
          // 设置激活
          this.$refs.tree.setCurrentKey(data.id);
          // 抛出数据
          this.$emit("input", data);
          // 抛出node
          this.$emit("update:node", node);
          // this.$parent[this.queryName](data.id);
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.tree ::v-deep {
  background: #f6f5f7;

  .inputs {
    padding: 20px 10px 0 10px;
  }
  // border-right: 1px solid gainsboro;
  width: 240px;
  height: calc(100vh - 178px);
  .el-tree {
    background: #f6f5f7;
    .el-tree-node__content:hover,
    .el-upload-list__item:hover {
      background-color: #2c66ab !important;
      span.name {
        color: #fff !important;
      }
      span.tag {
        color: #fff !important;
      }
    }
    .el-tree-node__content {
      .el-tree-node__expand-icon {
        color: #000;
        font-size: 13px;
        &.is-leaf {
          color: transparent;
        }
      }
    }
    .el-tree-node.is-current.is-focusable {
      & > .el-tree-node__content {
        background-color: #2c66ab !important;
        span.name {
          color: #fff !important;
        }
        span.tag {
          color: #fff !important;
        }
      }
    }
  }
  .tree-box {
    margin-top: 10px;
    overflow-y: scroll;
    position: relative;
    height: calc(100% - 60px);
    &::-webkit-scrollbar {
      display: none;
    }
    font-size: 14px;
    .el-tree-node__expand-icon:not(.is-leaf) {
      color: #232b31 !important;
    }
    // 超出隐藏
    .custom-tree-node {
      span.name {
        max-width: 160px;
        min-width: 160px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #232b31;
      }
      .box {
        display: flex;
        align-content: center;
        gap: 0 4px;
        .tag {
          border: 1px solid #227fb5;
          font-size: 10px;
          padding: 0 2px;
          transform: scale(0.8);
        }
      }
    }
  }
}
</style>
